package com.syni.mdd.sjb.common.component.utils.common.utils;

import com.syni.mdd.sjb.common.component.utils.common.constants.CommonResultCode;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @className RequestParamUtils
 * @description 检查参数工具类
 * @Author cfx
 * @DATE 2019/4/11 15:52
 * @VERSION 1.0
 **/
public class RequestParamUtils {

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request;
    }

    public static Map<String, Object> checkRequestParams(Map<String, Object> paramsMap, Map<String, Object> needCheckParam) {
        if (needCheckParam != null && needCheckParam.size() > 0) {
            for (Map.Entry<String, Object> argsEntry : needCheckParam.entrySet()) {
                if (!paramsMap.containsKey(argsEntry.getKey())) {
                    return ResultMapHelper.failure(argsEntry.getValue().toString());
                }
            }
        }
        return ResultMapHelper.success();
    }

    public static Map<String, Object> checkParams(Map<String, Object> paramsMap, String... args) {
        if (args.length > 0) {
            for (String arg : args) {
                if (!(paramsMap.containsKey(arg) && StringUtils.checkNullAndEmpty(arg))) {
                    return ResultMapHelper.result(CommonResultCode.CODE_ERROR_03, "业务参数缺失" + arg);
                }
            }
        }
        return ResultMapHelper.success();
    }

    public static Map<String, String> getWxPayData(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        if (request != null) {
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
                // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
                params.put(name, valueStr);
            }
        }
        return params;
    }
}
